<template>
  <v-container>
    <!-- <div v-if="isAdmin" style="background-image: url('/img/login_bg.jpg');background-size: 100% 100%;width: 100%;height: 100%;display: flex;
  flex-direction: column;align-items: center;justify-content: center;">
      <img src="/img/avatar.png" alt="" style="width: fit-content;height: fit-content;">
      <h1 style="color: red;text-align: center;">你干嘛~这是后台管理，闲人免进！</h1>
    </div> -->
    <div :style="{ 'height': containerHeight + 'px', 'overflow-y': 'auto' }">
      <v-row>
        <v-col sm="12">
          <div id="weeklyApiView" style="width: 100%;height: 400px;"></div>
        </v-col>
      </v-row>
      <v-row>
        <v-col sm="12">
          <div id="dayHourApiView" style="width: 100%;height: 400px;"></div>
        </v-col>
      </v-row>
      <v-row>
        <v-col sm="12">
          <div id="wordLanguagePieView" style="width: 100%;height: 400px;"></div>
        </v-col>
      </v-row>
    </div>
  </v-container>
</template>

<script>
import { getHourApiAggregationData, getLanguageWordPieView, getWeeklyApiAggregationData } from '@/api/aggregate';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      containerHeight: 800,
      isAdmin: false,
      weeklyApiViewChart: undefined,
      wordLanguagePieViewChart: undefined,
      dayHourApiViewChart: undefined,
      weeklyApiViewOption: {
        title: {
          text: "最近15天内接口访问数",
          left: 'center',
          textStyle: {
            fontSize: 20
          },
        },
        xAxis: {
          type: 'category',
          data: ['1', '2', '3', '4', '5', '6', '7','8','9','10','11','12','13','14','15'],
          axisLabel: {
            interval: 0,
            rotate: 40
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0,0],
            type: 'line',
            smooth: true,
            // areaStyle: {},
            label: {
              show: true,
              position: 'top',
              textStyle: {
                fontSize: 20
              }
            }
          }
        ]
      },
      dayHourApiViewOption: {
        title: {
          text: "24小时内接口访问数",
          left: 'center',
          textStyle: {
            fontSize: 20
          },
        },
        xAxis: {
          type: 'category',
          data: ['0', '1', '2', '3', '4', '5', '6', '7', '9', '10', '11', '12'],
          axisLabel: {
            interval: 0,
            rotate: 40
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            type: 'line',
            smooth: true,
            // areaStyle: {},
            label: {
              show: true,
              position: 'top',
              textStyle: {
                fontSize: 20
              }
            }
          }
        ]
      },
      wordLanguagePieOption: {
        title: {
          text: '系统单词语种分类及数量',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            // name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 300, name: 'word' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  },
  mounted() {
    this.containerHeight = window.innerHeight - 64
    this.initChartView()
    this.getWeeklyApiViewData()
    this.getLanguageWordPieViewData()
    this.getHoursApiViewData()
  },
  methods: {
    initChartView() {
      let weeklyApiViewDom = document.getElementById('weeklyApiView')
      this.weeklyApiViewChart = echarts.init(weeklyApiViewDom)
      this.weeklyApiViewChart.setOption(this.weeklyApiViewOption)
      let wordLanguagePieView = document.getElementById('wordLanguagePieView')
      this.wordLanguagePieViewChart = echarts.init(wordLanguagePieView)
      this.wordLanguagePieViewChart.setOption(this.wordLanguagePieOption)
      let dayHourApiView = document.getElementById('dayHourApiView')
      this.dayHourApiViewChart = echarts.init(dayHourApiView)
      this.dayHourApiViewChart.setOption(this.dayHourApiViewOption)
      // window.addEventListener('resize', function () {
      //   this.weeklyApiViewChart.resize();
      // });
    },
    getWeeklyApiViewData() {
      let dateSpan = this.getDateSpan()
      let dateList = this.generateDates(dateSpan.startTimestamp, dateSpan.endTimestamp)
      let seriesData = []
      this.weeklyApiViewOption.xAxis.data = dateList
      this.weeklyApiViewChart.setOption(this.weeklyApiViewOption)
      getWeeklyApiAggregationData({
        startTime: dateSpan.startTimestamp, endTime: dateSpan.endTimestamp
      }).then(resp => {
        if(resp.data==null)return 
        let viewDataIndex = 0
        for (let i = 0; i < dateList.length; i++) {
          if (dateList[i] === resp.data[viewDataIndex].dateStr) {
            seriesData.push(resp.data[viewDataIndex].count)
            viewDataIndex++
          } else seriesData.push(0)
        }
        this.weeklyApiViewOption.series[0].data = seriesData
        this.weeklyApiViewChart.setOption(this.weeklyApiViewOption)
      })
    },
    getHoursApiViewData() {
      let hourSpan = this.getDateHoursSpan()
      let hourSpanList = this.generateDateHour(hourSpan.startTimestamp, hourSpan.endTimestamp)
      this.dayHourApiViewOption.xAxis.data = hourSpanList
      this.dayHourApiViewChart.setOption(this.dayHourApiViewOption)
      let seriesData = []
      getHourApiAggregationData({
        startTime: hourSpan.startTimestamp, endTime: hourSpan.endTimestamp
      }).then(resp => {
        if(resp.data==null)return 
        let viewDataIndex = 0
        for (let i = 0; i < hourSpanList.length; i++) {
          if (hourSpanList[i] === resp.data[viewDataIndex].dateStr) {
            seriesData.push(resp.data[viewDataIndex].count)
            viewDataIndex++
          } else seriesData.push(0)
        }
        this.dayHourApiViewOption.series[0].data = seriesData
        this.dayHourApiViewChart.setOption(this.dayHourApiViewOption)
      })
    },
    getLanguageWordPieViewData() {
      getLanguageWordPieView().then(resp => {
        if(resp.data==null)return 
        let pieData = []
        for (let index = 0; index < resp.data.length; index++) {
          pieData.push({
            name: resp.data[index].lang,
            value: resp.data[index].count
          })
        }
        this.wordLanguagePieOption.series[0].data = pieData
        this.wordLanguagePieViewChart.setOption(this.wordLanguagePieOption)
      })
    },
    generateDates(startDate, endDate) {
      // 将字符串转换为Date对象
      startDate = new Date(startDate);
      endDate = new Date(endDate);

      // 创建一个空数组来保存结果
      let dates = [];
      let currentDate = startDate;

      // 使用while循环来生成日期
      while (currentDate <= endDate) {
        // 日期格式化为yyyy-MM-dd
        let year = currentDate.getFullYear();
        let month = ("0" + (currentDate.getMonth() + 1)).slice(-2); // 月份从0开始，所以加1
        let day = ("0" + currentDate.getDate()).slice(-2);
        let formattedDate = year + "-" + month + "-" + day;

        dates.push(formattedDate);
        // 增加一天
        currentDate.setDate(currentDate.getDate() + 1);
      }
      return dates;
    },
    generateDateHour(startTime, endTime) {
      // 将字符串转换为Date对象
      let startDate = new Date(startTime);
      let endDate = new Date(endTime);

      // 创建一个空数组来保存结果
      let dates = [];
      let currentDate = startDate;

      // 使用while循环来生成日期
      while (currentDate <= endDate) {
        // 日期格式化为yyyy-MM-dd
        let year = currentDate.getFullYear();
        let month = ("0" + (currentDate.getMonth() + 1)).slice(-2); // 月份从0开始，所以加1
        let day = ("0" + currentDate.getDate()).slice(-2);
        let hour = ("0" + currentDate.getHours()).slice(-2);
        let formattedDate = year + "-" + month + "-" + day + ' ' + hour;

        dates.push(formattedDate);
        // 增加一天
        currentDate.setHours(currentDate.getHours() + 1);
      }
      return dates;
    },
    getDateSpan(nowDate) {
      if (nowDate === undefined) nowDate = new Date();
      let endDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 23, 59, 59)
      let startDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate())
      startDate.setDate(startDate.getDate() - 15)
      // console.log(startDate,endDate)
      return {
        startTimestamp: startDate.getTime(), endTimestamp: endDate.getTime()
      }
    },
    getDateHoursSpan(nowTime) {
      if (nowTime === undefined) nowTime = new Date();
      let startTime = new Date(nowTime.getFullYear(), nowTime.getMonth(), nowTime.getDate(),nowTime.getHours(),0,0)
      startTime.setHours(startTime.getHours() - 24)
      nowTime.setMinutes(59)
      nowTime.setSeconds(59)
      nowTime.setMilliseconds(999)
      return {
        startTimestamp: startTime.getTime(), endTimestamp: nowTime.getTime()
      }
    }
  }
}
</script>

<style scoped>
@media (min-width: 1280px) {
  .v-container {
    max-width: 100%;
    padding: 10px;
  }
}
</style>